import { StrTool } from '@es-tool/core'

/**
 * 通用响应对象
 * Response
 * @author LL
 * @date 2022-01-18 下午 02:15
 **/
export class Response<T = any> {

    public static CODE_OK: number = 0
    public static CODE_FAILURE: number = -1

    public code: number
    public msg: string
    public data: T

    constructor(code: number, msg: string, data: T) {
        this.code = code
        this.msg = msg
        this.data = data
    }

    // @ts-ignore
    public static ok<T>(msg = StrTool.EMPTY, data: T = null): Response {
        return new Response<T>(this.CODE_OK, msg, data)
    }

    // @ts-ignore
    public static error<T = null>(msg = StrTool.EMPTY, data: T = null): Response {
        return new Response<T>(this.CODE_FAILURE, msg, data)
    }

    // noinspection JSValidateJSDoc
    /**
     * 如果响应成功, 获取响应数据
     * 否则 抛出异常
     * @param {Response<T>} res 目标响应对象
     * @return {T} 响应数据
     * @exception Error 如果响应为失败
     */
    public static getData<T>(res: Response<T>) {
        if (res.code === this.CODE_OK) {
            return res.data
        }
        throw new Error(res.msg)
    }
}
